package controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import entity.AfterSaleRule;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import service.AfterSaleRuleService;
import service.impl.AfterSaleRuleServiceImpl;

import java.io.IOException;
import java.io.PrintWriter;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet("/api/rule/*")
public class AfterSaleRuleServlet extends HttpServlet {
    private final ObjectMapper objectMapper = new ObjectMapper();
    private final AfterSaleRuleService ruleService = new AfterSaleRuleServiceImpl();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();
        Map<String, Object> result = new HashMap<>();

        try {
            String pathInfo = request.getPathInfo();
            HttpSession session = request.getSession();
            String role = (String) session.getAttribute("role");

            if (pathInfo == null || "/".equals(pathInfo)) {
                // 获取所有规则
                List<AfterSaleRule> rules = ruleService.getAllRules();
                result.put("success", true);
                result.put("data", rules);
            } else if (pathInfo.startsWith("/detail/")) {
                // 获取规则详情
                Long ruleId = Long.parseLong(pathInfo.substring(8));
                AfterSaleRule rule = ruleService.getRuleById(ruleId);
                
                if (rule == null) {
                    throw new Exception("规则不存在");
                }
                
                result.put("success", true);
                result.put("data", rule);
            } else {
                throw new Exception("无效的请求路径");
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", e.getMessage());
        }

        out.write(objectMapper.writeValueAsString(result));
        out.flush();
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();
        Map<String, Object> result = new HashMap<>();

        try {
            HttpSession session = request.getSession();
            String role = (String) session.getAttribute("role");

            if (!"OPERATOR".equals(role)) {
                throw new Exception("只有运营人员可以创建规则");
            }

            // 解析请求参数
            String ruleName = request.getParameter("ruleName");
            String ruleContent = request.getParameter("ruleContent");
            String category = request.getParameter("category");
            Boolean isActive = Boolean.parseBoolean(request.getParameter("isActive"));

            // 创建规则
            AfterSaleRule rule = new AfterSaleRule();
            rule.setRuleName(ruleName);
            rule.setRuleContent(ruleContent);
            rule.setCategory(category);
            rule.setIsActive(isActive);
            rule.setCreateTime(LocalDateTime.now());
            rule.setUpdateTime(LocalDateTime.now());

            // 保存规则
            ruleService.createRule(rule);

            result.put("success", true);
            result.put("message", "规则创建成功");
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", e.getMessage());
        }

        out.write(objectMapper.writeValueAsString(result));
        out.flush();
    }

    @Override
    protected void doPut(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();
        Map<String, Object> result = new HashMap<>();

        try {
            String pathInfo = request.getPathInfo();
            HttpSession session = request.getSession();
            String role = (String) session.getAttribute("role");

            if (!"OPERATOR".equals(role)) {
                throw new Exception("只有运营人员可以修改规则");
            }

            if (pathInfo == null || !pathInfo.startsWith("/update/")) {
                throw new Exception("无效的请求路径");
            }

            Long ruleId = Long.parseLong(pathInfo.substring(8));
            
            // 解析请求参数
            String ruleName = request.getParameter("ruleName");
            String ruleContent = request.getParameter("ruleContent");
            String category = request.getParameter("category");
            Boolean isActive = Boolean.parseBoolean(request.getParameter("isActive"));

            AfterSaleRule rule = ruleService.getRuleById(ruleId);
            if (rule == null) {
                throw new Exception("规则不存在");
            }

            // 更新规则
            rule.setRuleName(ruleName);
            rule.setRuleContent(ruleContent);
            rule.setCategory(category);
            rule.setIsActive(isActive);
            rule.setUpdateTime(LocalDateTime.now());

            ruleService.updateRule(rule);

            result.put("success", true);
            result.put("message", "规则更新成功");
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", e.getMessage());
        }

        out.write(objectMapper.writeValueAsString(result));
        out.flush();
    }

    @Override
    protected void doDelete(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();
        Map<String, Object> result = new HashMap<>();

        try {
            String pathInfo = request.getPathInfo();
            HttpSession session = request.getSession();
            String role = (String) session.getAttribute("role");

            if (!"OPERATOR".equals(role)) {
                throw new Exception("只有运营人员可以删除规则");
            }

            if (pathInfo == null || !pathInfo.startsWith("/delete/")) {
                throw new Exception("无效的请求路径");
            }

            Long ruleId = Long.parseLong(pathInfo.substring(8));
            
            AfterSaleRule rule = ruleService.getRuleById(ruleId);
            if (rule == null) {
                throw new Exception("规则不存在");
            }

            ruleService.deleteRule(ruleId);

            result.put("success", true);
            result.put("message", "规则删除成功");
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", e.getMessage());
        }

        out.write(objectMapper.writeValueAsString(result));
        out.flush();
    }
}
